package com.gs.common.sqlite

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.gs.common.data.User

class UserSqliteOpenHelper(
    context: Context?,
    name: String?,
    factory: SQLiteDatabase.CursorFactory?,
    version: Int,
) : SQLiteOpenHelper(context, name, factory, version) {

    private val db = writableDatabase

    constructor(context: Context) : this(context, DB_NAME, null, 1) {
    }

    override fun onCreate(db: SQLiteDatabase?) {
        // 创建表
        db?.execSQL(CREATE_TABLE_SQL)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {

    }

    fun addUser(user: User): Long {
        val userValues = ContentValues()
        userValues.put("phone_num", user.phoneNumber)
        userValues.put("user_name", user.userName)
        userValues.put("token", user.token)
        userValues.put("nickname", user.nickname)
        userValues.put("address", user.address)
        return db.insert(TABLE_NAME, null, userValues)
    }

    fun deleteUser(username: String): Int {
        return db.delete(TABLE_NAME, "user_name = ?", arrayOf(username))
    }

    fun deleteAll(): Int {
        return db.delete(TABLE_NAME, null,null)
    }

    fun selectUser(): List<User> {
        val list = ArrayList<User>()
        val cursor = db.query(TABLE_NAME, null, null, null, null, null, null)
        Log.d("size", "${cursor.count}")
        if (cursor.count != 0) {
            while (cursor.moveToNext()) {
                val id = cursor.getInt(0)
                val phoneNum = cursor.getString(1)
                val username = cursor.getString(2)
                val token = cursor.getString(3)
                val nickname = cursor.getString(4)
                val address = cursor.getString(5)

                val user = User(id = id, phoneNumber = phoneNum, userName = username, token = token, nickname = nickname, address = address)
                list.add(user)
            }
            cursor.close()
            return list
        }
        cursor.close()
        return list
    }



    companion object{
        private const val DB_NAME = "litchi_source.db"
        private const val TABLE_NAME = "user_tb"
        private const val CREATE_TABLE_SQL = "create table $TABLE_NAME (id integer primary key autoincrement, " +
                "phone_num varchar(11), user_name varchar(20), token text, nickname varchar(20), address varchar(255));"

    }
}